package singleton;

/**
 * 六种方式实现单例
 * @author MacBook
 *
 */
public class ClassicSingleton {

}
//线程不安全
class SingletonA{
	//饿汉式
	//比喻这个汉子很饿，一上来就new出了实例
	private static SingletonA instance = new SingletonA();
	private SingletonA(){
		
	}
	public static SingletonA getInstance(){
		return instance;
	}
}
//线程安全，性能低下
class SingletonB{
	//懒汉式
	//这个汉子很懒，不调用什么都不干，只有调用的时候才实例化
	private static SingletonB instance = null;
	private SingletonB(){
		
	}
	public static synchronized SingletonB  getInstance(){
		return (instance == null)?(instance = new SingletonB()):instance;
	}
}
//双重锁模式 DCL
class SingletonC{
	private static SingletonC instance = null;
	private SingletonC(){
		
	}
	//双重验证保证新建对象只有一个
	public static SingletonC getInstance(){
		if(instance == null)
			synchronized (SingletonC.class) {
				if(instance == null)
					instance = new SingletonC();
			}
		return instance;
	}
}
//静态内部类的实现
class SingletonD{
	private SingletonD(){
	}
	private static class InstanceLoader{
		private static final SingletonD instance = new SingletonD();
	}
	public static SingletonD getInstance(){
		return InstanceLoader.instance;
	}
}
//枚举模式 见EnumSingleton
//容器模式 使用map管理单例